package front

import (
	"geekai/api/dto/request"
	"geekai/api/handler"
	"geekai/core"
	"geekai/core/types"
	"geekai/service/openai/chat"
	"geekai/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type ChatOpenAiHandler struct {
	handler.BaseHandler
	openAiChatService *chat.OpenAiChatService
}

func NewChatOpenAiHandler(app *core.AppServer, db *gorm.DB, openAiChatService *chat.OpenAiChatService) *ChatOpenAiHandler {
	return &ChatOpenAiHandler{
		BaseHandler:       handler.BaseHandler{App: app, DB: db},
		openAiChatService: openAiChatService,
	}
}

// Tokens godoc
// @Summary      统计 token 数量
// @Description  统计 token 数量
// @Tags         前台-用户会话
// @Accept       json
// @Produce      json
// @Param        req   body     request.ChatTokens  true  "统计tokens数量参数"
// @Success      200  {object}  types.BizVo{data=int}
// @Router       /api/chat/tokens [post]
// @Security ApiKeyAuth
func (h *ChatOpenAiHandler) Tokens(c *gin.Context) {
	var data request.ChatTokens
	if err := c.ShouldBindJSON(&data); err != nil {
		utils.ERROR(c, types.InvalidArgs)
		return
	}
	// 计算token
	tokens, err := utils.CalcTokens(data.Text, data.Model)
	if err != nil {
		log.Errorf("计算token失败：%v", err)
		return
	}
	utils.SUCCESS(c, tokens)
}

// StopGenerate godoc
// @Summary      停止生成
// @Description  停止生成
// @Tags         前台-用户会话
// @Accept       json
// @Produce      json
// @Param        client_id   query     string  true  "会话Id"
// @Success      200  {object}  types.BizVo{}
// @Router       /api/chat/stop [get]
// @Security ApiKeyAuth
func (h *ChatOpenAiHandler) StopGenerate(c *gin.Context) {
	clientId := h.GetTrim(c, "client_id")
	h.openAiChatService.StopGenerate(clientId)
	utils.SUCCESS(c, types.OkMsg)
}
